package com.wanchuang.hepos.help;

import android.app.Activity;
import android.util.Base64;

import androidx.fragment.app.Fragment;

import com.example.havi.util.GlideEngine;
import com.wanchuang.architecture.utils.Utils;
import com.wanchuang.hepos.BuildConfig;
import com.wanchuang.hepos.R;
import com.wanchuang.hepos.app.App;
import com.wanchuang.hepos.bridge.data.repository.Apis;
import com.wanchuang.hepos.net.NetworkManager;
import com.wanchuang.hepos.net.interfaces.OnUpLoadCallBack;
import com.google.protobuf.InvalidProtocolBufferException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/2/2 0002.
 * 封装选择头像 图片单选 多选 图片多张上传 单张上传
 * 图片选择后要在 onActivityResult 返回 请看示例
 *
 * @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 * super.onActivityResult(requestCode, resultCode, data);
 * if (resultCode == RESULT_OK) {
 * switch (requestCode) {
 * case PictureConfig.CHOOSE_REQUEST:
 * selectionMedia = PictureSelector.obtainMultipleResult(data);
 * mAdapter.clear();
 * mAdapter.addAll(selectionMedia);
 * recyclerView.setVisibility(View.VISIBLE);
 * break;
 * }
 * }
 * }
 */

public class ImageHelper {

    public static void browseImages(Activity activity, int position, List<LocalMedia> medias) {
        PictureSelector.create(activity).themeStyle(R.style.picture_default_style).openExternalPreview(position, medias);
    }

    public static void browseImages(Fragment fragment, int position, List<LocalMedia> medias) {
        PictureSelector.create(fragment).themeStyle(R.style.picture_default_style).openExternalPreview(position, medias);
    }

    //选择图片 多张 拍照+图片 selectionMedia选中的图片
    public static void showImagesChoose(Activity activity, List<LocalMedia> selectionMedia) {
        DialogUtils.showBottomMenuDialog(activity, "选择图片", "拍照", "相册", new DialogUtils.BottomMenuDialogImpl() {
            @Override
            public void onMenu1() {
                PictureSelector.create(activity)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onMenu2() {
                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofImage())
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .selectionMode(PictureConfig.MULTIPLE)
                        .compress(true)
                        .enableCrop(false)
                        .selectionMedia(selectionMedia)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
    }

    //选择图片 多张 拍照+图片 selectionMedia选中的图片
    public static void showImagesChoose(Fragment fragment, List<LocalMedia> selectionMedia) {
        DialogUtils.showBottomMenuDialog(fragment.getContext(), "选择图片", "拍照", "相册", new DialogUtils.BottomMenuDialogImpl() {
            @Override
            public void onMenu1() {
                PictureSelector.create(fragment)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onMenu2() {
                PictureSelector.create(fragment)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .compress(true)
                        .enableCrop(false)
                        .selectionMedia(selectionMedia)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
    }

    //选择图片 单张
    public static void showImageChoose(Activity activity) {
        DialogUtils.showBottomMenuDialog(activity, "选择图片", "拍照", "相册", new DialogUtils.BottomMenuDialogImpl() {
            @Override
            public void onMenu1() {
                PictureSelector.create(activity)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .enableCrop(false)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onMenu2() {
                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofImage())
                        .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                        .compress(true)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
    }


    /**
     * 选择图片 单张
     *
     * @param fragment
     */
    public static void showImageChoose(Fragment fragment) {
        DialogUtils.showBottomMenuDialog(fragment.getContext(), "选择图片", "拍照", "相册", new DialogUtils.BottomMenuDialogImpl() {
            @Override
            public void onMenu1() {
                PictureSelector.create(fragment)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .enableCrop(false)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onMenu2() {
                PictureSelector.create(fragment)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .compress(true)
                        .enableCrop(false)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
    }

    //选择头像
    public static void showAvatarChoose(Activity activity) {
        DialogUtils.showBottomMenuDialog(activity, "选择头像", "拍照", "相册", new DialogUtils.BottomMenuDialogImpl() {
            @Override
            public void onMenu1() {
                PictureSelector.create(activity)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onMenu2() {
                PictureSelector.create(activity)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .compress(true)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
    }

    //选择头像
    public static void showAvatarChoose(Fragment fragment) {
        DialogUtils.showBottomMenuDialog(fragment.getContext(), "选择头像", "拍照", "相册", new DialogUtils.BottomMenuDialogImpl() {
            @Override
            public void onMenu1() {
                PictureSelector.create(fragment)
                        .openCamera(PictureMimeType.ofImage())
                        .compress(true)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void onMenu2() {
                PictureSelector.create(fragment)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .compress(true)
                        .enableCrop(true)
                        .withAspectRatio(1, 1)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
    }

    //选择头像
    public static void showSelectChoose(Fragment fragment) {
        PictureSelector.create(fragment)
                .openCamera(PictureMimeType.ofImage())
                .compress(true)
                .enableCrop(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    //上传单张
    public static void upLoadImage(String imagePath, OnUpLoadImageCallBack callBack) {
        NetworkManager.INSTANCE.upLoadFile(BuildConfig.SERVERHEAD + Apis.uploadImage, "file", new File(imagePath), new OnUpLoadCallBack() {
            @Override
            public void onOk(String response) throws InvalidProtocolBufferException {
                callBack.onSuccess(response);
            }

            @Override
            public void onError(int code, String errorMessage) {
                callBack.onFail(errorMessage);
            }

            @Override
            public void upProgress(int progress) {

            }
        });
    }

    //上传多张
    public static void upLoadImages(List<LocalMedia> images, OnUpLoadImagesCallBack callBack) {
        List<String> upLoadSuccessImages = new ArrayList<>();
        upLoad(upLoadSuccessImages, images, images.get(0).getCompressPath(), 0, callBack);
    }

    private static void upLoad(List<String> upLoadSuccessImages, List<LocalMedia> images, String file, int position, OnUpLoadImagesCallBack callBack) {
//        showProgress("正在上传" + (position + 1) + "/" + selectionMedia.size());
        NetworkManager.INSTANCE.upLoadFile(((App) (Utils.getApp())).getServiceHost() + Apis.uploadImage, "file", new File(file), new OnUpLoadCallBack() {
            @Override
            public void onOk(String response) {
                upLoadSuccessImages.add(response);
                int i = position + 1;
                if (i == images.size()) {
                    try {
                        callBack.onSuccess(upLoadSuccessImages);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    upLoad(upLoadSuccessImages, images, images.get(i).getCompressPath(), i, callBack);
                }
            }

            @Override
            public void onError(int code, String errorMessage) {
                callBack.onFail(errorMessage);
//                hideProgress();
//                showHintDialog("上传图片失败：" + errorMessage);
            }

            @Override
            public void upProgress(int progress) {

            }
        });
    }


    public static void upLoadImageBase64(String base64, OnUpLoadImageCallBack callBack) {
        NetworkManager.INSTANCE.upLoadFile(BuildConfig.SERVERHEAD + Apis.uploadImage, "file", base64ToFile(base64), new OnUpLoadCallBack() {
            @Override
            public void onOk(String response) throws InvalidProtocolBufferException {
                callBack.onSuccess(response);
            }

            @Override
            public void onError(int code, String errorMessage) {
                callBack.onFail(errorMessage);
            }

            @Override
            public void upProgress(int progress) {

            }
        });
    }




    public static File base64ToFile(String base64) {
        if (base64 == null || "".equals(base64)) {
            return null;
        }
        byte[] buff  = Base64.decode(base64,Base64.DEFAULT);
        File file = null;
        FileOutputStream out = null;
        try {
            file = File.createTempFile("tmp", null);
            out = new FileOutputStream(file);
            out.write(buff);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    public interface OnUpLoadImagesCallBack {
        void onSuccess(List<String> images) throws InterruptedException;

        void onFail(String error);
    }

    public interface OnUpLoadImageCallBack {
        void onSuccess(String images) throws InvalidProtocolBufferException;

        void onFail(String error);
    }

}
